package org.meetunexpectedly.service.file.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiniu.storage.model.FileInfo;
import org.meetunexpectedly.config.LocalCache;
import org.meetunexpectedly.config.QiNiuConfig;
import org.meetunexpectedly.entity.setting.Setting;
import org.meetunexpectedly.entity.video.File;
import org.meetunexpectedly.exception.BaseException;
import org.meetunexpectedly.mapper.video.FileMapper;
import org.meetunexpectedly.service.file.FileService;
import org.meetunexpectedly.service.file.QiNiuFileService;
import org.meetunexpectedly.service.setting.SettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

/**
 * @Description: 文件服务实现类
 * @Author: pupil
 * @Date: 2024/08/18 下午 6:47
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {

    @Autowired
    private QiNiuFileService qiNiuFileService;

    @Autowired
    private SettingService settingService;

    @Override
    public Long generatePhoto(Long fileId, Long userId) {
        // 根据视频的文件表id获取视频文件
        File file = getById(fileId);
        // 获取视频的播放的第一秒位置作为封面
        // 视频地址拼接?vframe/jpg/offset/1
        String fileKey = file.getFileKey() + "?vframe/jpg/offset/1";
        File fileInfo = new File();
        fileInfo.setFileKey(fileKey);
        fileInfo.setFormat("image/*");
        fileInfo.setType("图片");
        fileInfo.setUserId(userId);
        this.save(fileInfo);
        return fileInfo.getId();
    }

    @Override
    public Long save(String fileKey, Long userId) {
        // 判断文件
        FileInfo fileInfo = qiNiuFileService.getFileInfo(fileKey);

        if (fileInfo == null) {
            throw new IllegalArgumentException("参数不正确");
        }

        File file = new File();
        // 文件类型
        String type = fileInfo.mimeType;
        file.setFileKey(fileKey);
        file.setFormat(type);
        file.setType(type.contains("video") ? "视频" : "图片");
        file.setUserId(userId);
        file.setSize(fileInfo.fsize);
        this.save(file);

        return file.getId();
    }

    @Override
    public File getFileTrustUrl(Long fileId) {
        File file = this.getById(fileId);
        if (Objects.isNull(file)) {
            throw new BaseException("未找到该文件");
        }

        String url = QiNiuConfig.RealmName + "/" + file.getFileKey();

        Setting setting = settingService.list(null).get(0);
        // 判断是否开启回源鉴权
        if (setting.getAuth()) {
            // uuid用于授权的唯一标识
            String uuid = UUID.randomUUID().toString();
            // 将授权标识存储到本地缓存中
            LocalCache.put(uuid, true);

            if (url.contains("?")) {
                url = url + "&uuid=" + uuid;
            } else {
                url = url + "?uuid=" + uuid;
            }
        }

        file.setFileKey(url);
        return file;
    }
}
